package com.myl.generator.service.impl;

import com.baomidou.mybatisplus.core.metadata.TableFieldInfo;
import com.baomidou.mybatisplus.core.metadata.TableInfo;
import com.baomidou.mybatisplus.core.metadata.TableInfoHelper;
import com.baomidou.mybatisplus.extension.toolkit.Db;
import com.myl.generator.domain.model.ITableInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * DatabaseServiceImpl
 * author: myl <ixiaomu@qq.com>
 * tips:
 */
@Slf4j
@Service
public class DatabaseServiceImpl {

    @Autowired
    private JdbcTemplate jdbcTemplate;

    public String getDatabaseName() {
        String sql = "SELECT DATABASE()" ;
        return jdbcTemplate.queryForObject(sql, String.class);
    }

    /**
     * 获取当前库所有表信息
     *
     * @return
     */
    public Map<String, Object> getAllTable() {
        String databaseName = getDatabaseName();
        List<ITableInfo> tables = Db.lambdaQuery(ITableInfo.class)
                .eq(ITableInfo::getTableSchema, databaseName)
                .list();
        Map<String, Object> data = new HashMap<>();
        data.put("list", tables);
        return data;
    }

    public Map<String, Object> getTableColumns(String tableName) {
        TableInfo tableInfo = TableInfoHelper.getTableInfo(tableName);
        List<TableFieldInfo> columns = tableInfo.getFieldList().stream().toList();
        log.info("tableInfo: {}", columns);
        Map<String, Object> data = new HashMap<>();
        data.put("list" , columns);
        return data;
    }
}
